import { Category, Implementation, Tag } from '../types';

// 缓存管理
const cache = new Map<string, { data: any; timestamp: number }>();
const CACHE_DURATION = 5 * 60 * 1000; // 5分钟缓存

const getCachedData = <T>(key: string): T | undefined => {
  const cached = cache.get(key);
  if (cached && Date.now() - cached.timestamp < CACHE_DURATION) {
    return cached.data as T;
  }
  return undefined;
};

const setCachedData = <T>(key: string, data: T): void => {
  cache.set(key, { data, timestamp: Date.now() });
};

// 从本地JSON文件加载数据
const loadJsonData = async (path: string) => {
  try {
    const response = await fetch(path);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return await response.json();
  } catch (error) {
    console.error(`Error loading data from ${path}:`, error);
    throw error;
  }
};

// API服务
export const api = {
  // 获取所有分类
  getCategories: async (): Promise<Category[]> => {
    const cacheKey = 'categories';
    const cached = getCachedData<Category[]>(cacheKey);
    if (cached) return cached;

    try {
      const data = await loadJsonData('/data/categories.json');
      if (!data?.categories) {
        throw new Error('Invalid categories data format');
      }
      setCachedData<Category[]>(cacheKey, data.categories);
      return data.categories;
    } catch (error) {
      console.error('Error in getCategories:', error);
      throw error;
    }
  },

  // 获取所有标签
  getTags: async (): Promise<Tag[]> => {
    const cacheKey = 'tags';
    const cached = getCachedData<Tag[]>(cacheKey);
    if (cached) return cached;

    try {
      const data = await loadJsonData('/data/tags.json');
      if (!data?.tags) {
        throw new Error('Invalid tags data format');
      }
      setCachedData<Tag[]>(cacheKey, data.tags);
      return data.tags;
    } catch (error) {
      console.error('Error in getTags:', error);
      throw error;
    }
  },

  // 获取指定分类下的所有实现
  getCategoryImplementations: async (categoryId: string): Promise<Implementation[]> => {
    const cacheKey = `category_${categoryId}`;
    const cached = getCachedData<Implementation[]>(cacheKey);
    if (cached) return cached;

    try {
      const categories = await api.getCategories();
      const implementations: Implementation[] = [];
      
      // 查找当前分类
      const currentCategory = categories.find(c => c.id === categoryId) ||
        categories.flatMap(c => c.subCategories || []).find(sc => sc.id === categoryId);
      
      if (!currentCategory?.path) {
        console.warn(`No path found for category ${categoryId}`);
        return [];
      }

      try {
        // 加载目录下的所有 JSON 文件
        const files = await loadJsonData(`${currentCategory.path}/*.json`);
        if (Array.isArray(files)) {
          implementations.push(...files);
        } else if (files) {
          implementations.push(files);
        }
      } catch (error) {
        console.warn(`No implementations found in ${currentCategory.path}`);
      }

      // 如果是主分类，还需要加载子分类的实现
      if (!currentCategory.parentId && currentCategory.subCategories) {
        for (const subCategory of currentCategory.subCategories) {
          if (!subCategory.path) continue;
          
          try {
            const subFiles = await loadJsonData(`${subCategory.path}/*.json`);
            if (Array.isArray(subFiles)) {
              implementations.push(...subFiles);
            } else if (subFiles) {
              implementations.push(subFiles);
            }
          } catch (error) {
            console.warn(`No implementations found in ${subCategory.path}`);
          }
        }
      }

      setCachedData(cacheKey, implementations);
      return implementations;
    } catch (error) {
      console.error('Error in getCategoryImplementations:', error);
      throw error;
    }
  },

  // 获取单个实现的详细信息
  getImplementationById: async (implementationId: string): Promise<Implementation | null> => {
    const cacheKey = `implementation_${implementationId}`;
    const cached = getCachedData<Implementation | null>(cacheKey);
    if (cached) return cached;

    try {
      // 从ID中提取分类信息
      const [mainCategory, subCategory] = implementationId.split('-').slice(0, 2);
      const path = `/data/implementations/${mainCategory}/${subCategory}/${implementationId}.json`;
      
      const data = await loadJsonData(path);
      if (!data) {
        throw new Error(`Implementation ${implementationId} not found`);
      }

      setCachedData<Implementation>(cacheKey, data);
      return data;
    } catch (error) {
      console.error(`Error in getImplementationById for ${implementationId}:`, error);
      return null;
    }
  },

  // 根据标签获取实现列表
  getImplementationsByTag: async (tagId: string): Promise<Implementation[]> => {
    const cacheKey = `tag_${tagId}`;
    const cached = getCachedData<Implementation[]>(cacheKey);
    if (cached) return cached;

    try {
      const categories = await api.getCategories();
      const allImplementations: Implementation[] = [];
      
      for (const category of categories) {
        const implementations = await api.getCategoryImplementations(category.id);
        allImplementations.push(...implementations);
      }
      
      const filtered = allImplementations.filter(imp => imp.tags.includes(tagId));
      setCachedData<Implementation[]>(cacheKey, filtered);
      return filtered;
    } catch (error) {
      console.error(`Error in getImplementationsByTag for ${tagId}:`, error);
      throw error;
    }
  },

  // 搜索实现
  searchImplementations: async (query: string): Promise<Implementation[]> => {
    try {
      const categories = await api.getCategories();
      const allImplementations: Implementation[] = [];
      
      for (const category of categories) {
        const implementations = await api.getCategoryImplementations(category.id);
        allImplementations.push(...implementations);
      }
      
      const searchText = query.toLowerCase();
      return allImplementations.filter(imp => 
        imp.title.toLowerCase().includes(searchText) ||
        imp.description.toLowerCase().includes(searchText) ||
        imp.content.overview.toLowerCase().includes(searchText)
      );
    } catch (error) {
      console.error('Error in searchImplementations:', error);
      throw error;
    }
  },
};
